﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTO.Common;
using ServiceInterfaces.Headquarters;
using System.ServiceModel;

namespace GUI.Headquarter
{
    public partial class Products : System.Web.UI.Page
    {
        

        protected void Page_Load(object sender, EventArgs e)
        {
            TypeDropDownList.DataSource = Enum.GetNames(typeof(ProductType));
            TypeDropDownList.DataBind();

            try
            {
                ChannelFactory<IHeadquartersManagement> factory = new ChannelFactory<IHeadquartersManagement>("headquarter");
                IHeadquartersManagement headquarter = factory.CreateChannel();

                SupplierDropDownList.DataSource = from Supplier supp in headquarter.GetSuppliers()
                                                  select supp;
                SupplierDropDownList.DataTextField = "Name";
                SupplierDropDownList.DataValueField = "Number";

                SupplierDropDownList.DataBind();
            }
            catch (Exception excp)
            {
                this.ShowMessage(string.Format("Ocorreu um erro a carregar a página: {0}", excp.Message), MessageType.MessageDelay);
            }
        }

        protected void OnAddProduct(object sender, EventArgs e)
        {
            if (desig.Value.Length == 0 || price.Value.Length == 0 || stock.Value.Length == 0 || minStock.Value.Length == 0)
            {
                this.ShowMessage("Os campos 'Designação', 'Preço', 'Stock' e 'Stock Mínimo' são de preenchimento obrigatório", MessageType.Error);
                return;
            }

            /* OUTRAS VALIDACOES */
            if (price.Value.Contains(",")) {
                this.ShowMessage("O campo 'Preço' está mal formatado", MessageType.Error);
                return;
            }

            decimal pr = decimal.Parse(price.Value, new System.Globalization.CultureInfo("en-US"));

            try
            {
                Product prod = new Product
                {
                    Designation = desig.Value,
                    StockMin = int.Parse(minStock.Value),
                    Stock = int.Parse(stock.Value),
                    Price = pr,
                    Type  =  (ProductType)Enum.Parse(typeof(ProductType), TypeDropDownList.SelectedItem.Text, true),
                    Supplier = new Supplier{
                        Number = int.Parse(SupplierDropDownList.SelectedItem.Value),
                        Name   = SupplierDropDownList.SelectedItem.Text,
                        Address = String.Empty
                    }
                };

                ChannelFactory<IHeadquartersManagement> factory = new ChannelFactory<IHeadquartersManagement>("headquarter");
                IHeadquartersManagement headquarter = factory.CreateChannel();
                headquarter.AddProduct(prod);
                factory.Close();

                desig.Value = string.Empty;
                price.Value = string.Empty;
                minStock.Value = string.Empty;
                stock.Value = string.Empty;
                TypeDropDownList.SelectedIndex = 1;
                SupplierDropDownList.SelectedIndex = 1;

                this.ShowMessage("Produto adicionado com sucesso", MessageType.MessageDelay);
            }
            catch (Exception excp)
            {
                this.ShowMessage(string.Format("Ocorreu um erro ao tentar inserir o produto: {0}", excp.Message), MessageType.MessageDelay);
            }
        }

        protected void OnUpdateStock(object sender, EventArgs e)
        {
            if (productID.Value.Length == 0 || updStock.Value.Length == 0)
            {
                this.ShowMessage("Os campos 'ID do Produto' e 'Quantidade' são de preenchimento obrigatório", MessageType.Error);
                return;
            }

            try
            {
                ChannelFactory<IHeadquartersManagement> factory = new ChannelFactory<IHeadquartersManagement>("headquarter");
                IHeadquartersManagement headquarter = factory.CreateChannel();
                headquarter.UpdateStock(int.Parse(productID.Value), int.Parse(updStock.Value));
                factory.Close();

                productID.Value = string.Empty;
                updStock.Value = string.Empty;

                this.ShowMessage("Stock actualizado com sucesso", MessageType.MessageDelay);
            }
            catch (Exception excp)
            {
                this.ShowMessage(string.Format("Ocorreu um erro ao tentar actualizar o stock: {0}", excp.Message), MessageType.MessageDelay);
            }
        }
    }
}